 import Mqtt from './mqttTool.js'

class ChatService
{	
	/* 连接信息 */
	connectInfo = {
		clientId: 'Uniapp' + Date.parse(new Date()),
		url: 'wxs://192.168.1.6:8083/mqtt',
		clientId: 'abcdddd11231',
		clean: false
	}
	
	/* 订阅信息 */
	subscribeInfo = {
		topic: 'chat2',
		qos: 1
	}
	
	/* 日志信息 */
	isBuffer = false
	
	logs = [
		{option:'环境配置：', log:'配置成功'},
	]
	
	/* 发送信息 */
	isSending = false
	
	sendInfo = {
		msg: '',
		keyboard: 0
	}
	
	messages={}
	
	events = {}
	
	storage = null
	
	chatStore = null
	
	constructor(opt){
		// #ifdef MP-WEIXIN
			this.connectInfo.url = opt?.url ? opt.url :'wx://192.168.1.6:8083/mqtt'
		// #endif
		
		// #ifndef MP-WEIXIN
			this.connectInfo.url = opt?.url ? opt.url :'ws://192.168.1.6:8083/mqtt'
		// #endif
		
		
		this.storage = opt?.storage ? opt?.storage : {
			getItem:uni.getStorageSync,
			setItem:uni.setStorageSync
		},
		
		this.chatStore = opt?.chatStore ? this.chatStore : null
		this.mqtt = new Mqtt()	
	}
	
	start(clientId)
	{
		this.connectInfo.clientId = clientId
		
		this.log('Chat service started!')
		this.startConnect()
	}
	
	log(info)
	{
		console.log(typeof(info)=='object'?JSON.stringify(info):info)
	}
	
	on(event,func) {
		if(!this.events[event])
			this.events[event] = []
		
		this.events[event].push(func)
	}
	
	off(event,func)
	{
		if(!this.events[event]) return
		
		if(!func)
		{
			delete this.events[event]
			return
		}
		
		this.events[event] = this.events[event].filter((f)=> f != func)	
		
		if(this.events[event].length == 0) delete this.events[event]
	}
	
	notify(event,message)
	{
		const funcs = this.events[event]
		
		if(!funcs) return
		
		funcs.forEach((func)=>{
			func(message)
		})
	}
	
	topicStorageKEY(topic)
	{
		return `chat-storage:${this.connectInfo.clientId}:${topic}`
	}
	
	messagesWithTopic(topic) {
		console.log(this.topicStorageKEY(topic))
		let messages = this.storage.getItem(this.topicStorageKEY(topic))
		
		console.log(messages)
		console.log(typeof(messages))
		
		if(messages)
		{
			messages = JSON.parse(messages)
			messages = messages.map((m)=>JSON.parse(m))
		}
		else 
		{  
			messages = []
		}
		
		return messages
	}
	
	onMessage(topic, message, buffer)
	{
		if(!this.messages[topic])
			this.messages[topic] = []
		
		this.messages[topic].push(message.toString())

		let topicMessages = this.storage.getItem(this.topicStorageKEY(topic))
		
		if(topicMessages)
		    topicMessages = JSON.parse(topicMessages)
		else
			topicMessages = []
		  
		topicMessages.unshift(message.toString())
		  
		this.storage.setItem(this.topicStorageKEY(topic),JSON.stringify(topicMessages))
	
	    //chatStorage.push(topic,message)
		
		this.notify(topic,message.toString())
		
		// if(_this.isBuffer){
		// 	_this.log({option:topic+' buffer：', log: JSON.stringify(buffer)})
		// }
		// _this.log({option:topic+' message：', log: message.toString()})
	}
	
	// async sendMessage(topic,message)
	// {
	// 	return new Promise((resolve,reject)=>{
	// 		this.mqtt.publish({topic,message}).then(res =>{
	// 			 resolve(res)
	// 		})
	// 	})
	// }
	
	/* 连接 */
	async startConnect(){
		var _this = this
		let opts = {
			url: this.connectInfo.url,
			clientId: this.connectInfo.clientId,
			username: this.connectInfo.username,
			password: this.connectInfo.password,
			clean: this.connectInfo.clean,
			protocolVersion:4,
			reconnectPeriod:0,
			qos:1
		}
		var client = await this.mqtt.connect(opts).client;
		client.on('connect', function(res) {
			_this.log({option:'mqtt：', log:'连接成功'})
		})
		client.on('reconnect', function(res) {
			_this.log({option:'mqtt：', log:'重新连接'})
		})
		client.on('error', function(res) {
			_this.log({option:'mqtt：', log:'连接错误'})
			_this.mqtt.end()
		})
		client.on('close', function(res) {
			_this.log({option:'mqtt：', log:'关闭成功'})
		})
		client.on('message', function(topic, message, buffer) {
			_this.onMessage(topic,message,buffer)
		})
	}
	
	/* 终止连接 */
	endConnect(){
		var _this = this
		this.mqtt.end().then(res =>{
			_this.log({option:'终止：', log:res})
		})
	}
	
	/* 重新连接 */
	reConnect(){
		var _this = this
		this.mqtt.reconnect().then(res =>{
			_this.log({option:'重连：', log:res})
		})
	}
	
	/* 更改Qos */
	changeQos(){
		var _this = this
		if(this.subscribeInfo.qos >= 2){
			this.subscribeInfo.qos = 0
			this.log({option:'Qos：', log:this.subscribeInfo.qos + ' Qos变更，订阅已取消，请重新发起订阅'})
			this.endSubscribe();
		}else{
			this.subscribeInfo.qos += 1
			this.log({option:'Qos：', log:this.subscribeInfo.qos + ' Qos变更，订阅已取消，请重新发起订阅'})
			this.endSubscribe();
		}
	}
	
	/* 订阅 */
	startSubscribe(){
		if(this.subscribeInfo.topic == ''){
			uni.showToast({
				icon: 'none',
				title: '输入topic'
			})
			return;
		}
		var _this = this
		let opts = {
			topic: this.subscribeInfo.topic,
			qos: this.subscribeInfo.qos,
		}
		this.mqtt.subscribe(opts).then(res =>{
			_this.log({option:'订阅' + opts.topic + '：', log:res})
		})
	}
	/* 取消订阅 */
	endSubscribe(){
		var _this = this
		let opts = {
			topic: this.subscribeInfo.topic
		}
		this.mqtt.unsubscribe(opts).then(res =>{
			_this.log({option:'取消订阅：', log:res})
		})
	}
	
	/* 发送消息 */
	publish(topic,message){
		var _this = this
		let opts = {
			topic: topic,
			message: message,
			options:{
				qos:1
			}
		}
		this.mqtt.publish(opts).then(res =>{
			_this.sendInfo.msg = ''
			_this.log({option:'发送：', log:res})
		})
	}
}

export default ChatService